<template>
  <div class="app-container pg-oms-workorder-list">
    <!-- page-tab-box begin -->
    <div ref="pageTab" class="page-tab-box">
      <el-tabs v-model="activeName">
        <el-tab-pane v-for="(item, index) in tabList" :key="`tab-${index}`" :name="item.name">
          <div class="tab-label" slot="label">
            <span class="label-name">{{ item.label }}</span>
            <span class="label-tip bg_red" v-if="item.name === 'returned'">{{ item.quantity }}</span>
            <span class="label-tip" v-else>{{ item.quantity }}</span>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- page-tab-box end -->
    <!-- top-search begin -->
    <div ref="topSearch" class="top-search top-more-search" v-show="showSearch">
      <el-form
        inline
        ref="searchForm"
        label-width="0"
        class="search-form"
        :class="{ 'show-more': showFormMore }"
        :model="searchForm">
        <el-form-item prop="warehouse">
          <el-input
            v-model="searchForm.warehouse"
            clearable
            placeholder="请输入仓库名称"
            @keyup.enter.native="search()"></el-input>
        </el-form-item>
        <div class="append-item">
          <el-form-item class="append-l" prop="alOrderInput">
            <el-select v-model="searchForm.alOrderType" placeholder="请选择" @change="search()">
              <el-option label="阿里单号" value="alOrder" />
              <el-option label="运单号" value="logisticsOrder" />
              <el-option label="订单号" value="orderNo" />
              <el-option label="物流单号" value="referenceNo" />
              <el-option label="主单号" value="carrierBillNo" />
              <el-option label="箱号" value="carrierBoxNo"> </el-option>
            </el-select>
          </el-form-item>
          <el-form-item class="append-r" prop="alOrderInput">
            <el-input v-model="searchForm.alOrderInput" placeholder="请输入" clearable @keyup.enter.native="search()" />
          </el-form-item>
        </div>
        <div class="append-item">
          <el-form-item class="append-l" prop="receiverType">
            <el-select v-model="searchForm.receiverType">
              <el-option label="收件国家" value="consigneeCountryName" />
              <el-option label="收件邮编" value="consigneePostalCode" />
              <el-option label="收件城市" value="consigneeCity" />
              <el-option label="收件人" value="consigneeName1" />
              <el-option label="收件电话" value="consignorMobile" />
            </el-select>
          </el-form-item>
          <el-form-item class="append-r" prop="receiverInput">
            <el-input v-model="searchForm.receiverInput" placeholder="请输入" clearable @keyup.enter.native="search()" />
          </el-form-item>
        </div>
        <div class="search-more-item" v-show="isBigWindow || showFormMore">
          <el-form-item prop="isWeighted">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.isWeighted"
              clearable
              placeholder="是否核重"
              @change="search()" />
          </el-form-item>
        </div>
        <div class="search-more-item" v-show="showFormMore">
          <el-form-item prop="confirmStatus">
            <el-select v-model="searchForm.confirmStatus" placeholder="修改待确认" clearable @change="search()">
              <el-option label="待确认" value="1" />
              <el-option label="已确认" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="pushExpense">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.pushExpense"
              clearable
              placeholder="是否推费"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="paymentStatus">
            <el-select v-model="searchForm.paymentStatus" placeholder="是否支付" clearable @change="search()">
              <el-option label="已支付" value="1" />
              <el-option label="未支付" value="0" />
            </el-select>
          </el-form-item>
          <el-form-item prop="trackStatus">
            <dg-dict-select
              dictType="ali_order_type"
              v-model="searchForm.trackStatus"
              clearable
              placeholder="跟踪状态"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="productId">
            <dg-service-select
              class="w-full"
              placeholder="运输产品"
              v-model="searchForm.productId"
              :dataType="20002"
              filterable
              clearable
              @change="search()" />
          </el-form-item>
          <el-form-item prop="hasWorkOrder">
            <dg-dict-select
              dictType="yes_no"
              v-model="searchForm.hasWorkOrder"
              clearable
              placeholder="是否有工单"
              @change="search()" />
          </el-form-item>
          <el-form-item prop="dateRange">
            <el-date-picker v-model="searchForm.dateRange" type="daterange" unlink-panels range-separator="-"
              start-placeholder="下单开始日期" end-placeholder="下单截止日期" value-format="yyyy-MM-dd HH:mm:ss" clearable
              :picker-options="pickerOptions" :default-time="['00:00:00', '23:59:59']" @change="search()">
            </el-date-picker>
          </el-form-item>
        </div>
        <el-form-item class="search-btn-part">
          <el-button type="primary" @click="search()">查询</el-button>
          <el-button @click="resetQuery()">重置</el-button>
          <el-button class="more-btn" type="text" @click="searchShowMore()">{{ !showFormMore ? '更多搜索' : '收起'
          }}<span class="ml5" :class="`el-icon-arrow-${!showFormMore ? 'down' : 'up'}`"></span></el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- top-search end -->
    <!-- right-toolbar begin -->
    <right-toolbar ref="rightToolbar" :showSearch.sync="showSearch" :tableColumn.sync="tableColumn" tableName="oms_cargo_question_record" @queryTable="search()">
      <template v-slot:operaBar>
        <el-button v-if="activeName=='pending_outbound'" type="primary" @click="showUpdateProduct()">修改运输产品</el-button>
        <el-button type="primary" @click="downstream()">对接下游</el-button>
        <el-button type="primary" @click="calculateExpense()">计算运费</el-button>
        <el-button type="primary" @click="pushExpense()">推送费用</el-button>
        <el-button type="danger" plain @click="confirmOrder()">修改确认</el-button>
        <el-button type="primary" plain @click="trackBatchHandle()">批量跟踪</el-button>
        <template v-if="activeName=='shipped'">
          <el-button type="primary" plain @click="print()">打印标签</el-button>
          <el-button type="primary" plain @click="downLoadLabel()">下载标签</el-button>
        </template>
        <el-button type="primary" plain @click="pushAgainCarrierToCW()">二次推送面单及转单号到中心仓</el-button>
        <el-button type="warning" plain>导出</el-button>
        <el-button type="danger" plain @click="submitWorkOrder()">提交中心仓工单</el-button>
      </template>
    </right-toolbar>
    <!-- right-toolbar end -->
    <!-- table begin -->
    <el-table ref="pageTable" class="page-table border-all mt10"
      :data="tableData" :row-key="getRowKeys"
      @selection-change="tableSelect"
      show-summary :summary-method="getSummaries"
      :height="tableHeight" border stripe>
      <el-table-column type="selection" width="32" fixed></el-table-column>
      <template v-for="(item, iindex) in tableColumn">
        <el-table-column v-if="filterArrs.includes(item.field)"
          show-overflow-tooltip
          :key="`filter-${iindex}`"
          :label="item.columnTitle"
          :prop="item.columnProperty"
          :width="item.columnWidth">
          <template slot-scope="scope">
            <span>{{ scope.row[item.field] | filterDict(dict.type[item.field=='trackStatus'?'ali_order_type':item.field=='checkWeightStatus'?'check_weight_status':'yes_no']) }}</span>
          </template>
        </el-table-column>
        <el-table-column v-else
          show-overflow-tooltip
          :key="`default-${iindex}`"
          :label="item.columnTitle"
          :prop="item.columnProperty"
          :width="item.columnWidth"
          :fixed="item.field=='orderCode'" />
      </template>
      <!-- <el-table-column show-overflow-tooltip prop="aliOrderNo" label="阿里订单号" align="center" width="150" fixed></el-table-column>
      <el-table-column show-overflow-tooltip prop="orderNo" label="订单号" align="center" width="150"></el-table-column>
      <el-table-column show-overflow-tooltip prop="productName" label="运输产品" align="center" width="130"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneeCountryName" label="收货国家" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="trackStatus" label="跟踪状态" align="center" width="88">
        <template slot-scope="scope">
          <span>{{ scope.row.trackStatus | filterDict(dict.type['ali_order_type']) }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="referenceNo" label="物流单号" align="center" width="150"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consignorName1" label="发货客户" align="center" width="100"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consignorCity" label="发货城市" align="center" width="100"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consignorPostalCode" label="发货邮编" align="center" width="100"></el-table-column>
      <el-table-column show-overflow-tooltip prop="warehouseName" label="仓库" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneeName1" label="收货人" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneeCity" label="收货城市" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneePostalCode" label="收货邮编" align="center" width="100"></el-table-column>
      <el-table-column show-overflow-tooltip prop="consigneeTelephone" label="收货电话" align="center" width="150"></el-table-column>
      <el-table-column show-overflow-tooltip prop="nextDown" label="下家" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="carrierChannelName" label="渠道" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="carrierBustNo" label="转单号" align="center" width="120"></el-table-column>
      <el-table-column show-overflow-tooltip prop="pushExpense" label="是否推费" align="center" width="70">
        <template slot-scope="scope">
          <span>{{ scope.row.pushExpense | filterDict(dict.type['yes_no']) }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="payStatus" label="是否支付" align="center" width="70">
        <template slot-scope="scope">
          <span>{{ scope.row.payStatus | filterDict(dict.type['yes_no']) }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="totalWeight" label="重量" align="center" width="72"></el-table-column>
      <el-table-column show-overflow-tooltip prop="totalVolume" label="体积" align="center" width="72"></el-table-column>
      <el-table-column show-overflow-tooltip prop="billTrafic" label="计费重量" align="center" width="72"></el-table-column>
      <el-table-column show-overflow-tooltip prop="totalExpense" label="费用合计" align="center" width="72"></el-table-column>
      <el-table-column show-overflow-tooltip prop="checkWeightStatus" label="是否核重" align="center" width="70">
        <template slot-scope="scope">
          <span>{{ scope.row.checkWeightStatus | filterDict(dict.type['check_weight_status']) }}</span>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip prop="cancelRemarks" label="取消备注" align="center" width="200"></el-table-column>
      <el-table-column show-overflow-tooltip prop="transferNumber" label="工单问题" align="center" width="120"></el-table-column>
      <el-table-column label="操作" width="112" fixed="right">
        <template slot-scope="scope">
          <div class="opera-row">
            <el-button type="text" class="opera-item" @click="handleDetail(scope.row.id)">详情</el-button>
            <el-button type="text" class="opera-item" @click="handleTrack(scope.row)">跟踪</el-button>
            <el-button v-if="scope.row.orderStatus==-2" type="text" class="opera-item" @click="showReturnDetail(scope.row.id)">退货
            </el-button>
            <el-button type="text" class="opera-item" @click="handleExpense(scope.row.id)">运费</el-button>
          </div>
        </template>
      </el-table-column> -->
    </el-table>
    <!-- table begin -->
    <!-- page-pagination begin -->
    <pagination
      class="page-pagination"
      :total="total"
      :page-size="pageSize"
      :page-index="pageIndex"
      @change="pageChange">
    </pagination>
    <!-- page-pagination end -->

    <!-- dialog-order-track begin -->
    <dialog-order-track :show.sync="dialogTrack" :order="trackOrder" @refresh="search" />
    <!-- dialog-order-track end -->
    <!-- dialog-waybill-expense begin -->
    <dialog-waybill-expense :show.sync="dialogOrderExpense" :id="orderId" />
    <!-- dialog-waybill-expense end -->
  </div>
</template>

<script>
import mixin from '@/utils/filtermixin/mixin';
import listmixin from '@/utils/list-mixin';
import { Foundation } from '@/utils/index';
import DialogOrderTrack from '../components/dialog-order-track';
import DialogWaybillExpense from '../components/dialog-waybill-expense';
import * as API_Order from '@/api/aliorder/order';
export default {
  name: 'pg-oms-workorder-list',
  components: {
    DialogOrderTrack,
    DialogWaybillExpense
  },
  dicts: ['ali_order_type', 'yes_no', 'check_weight_status'],
  mixins: [mixin, listmixin],
  data () {
    return {
      // tab
      tabList: [
        { label: '全部', name: 'sum', quantity: 0 },
        { label: '待入库', name: 'pending_inbound', quantity: 0 },
        { label: '待出库', name: 'pending_outbound', quantity: 0 },
        { label: '已发运', name: 'shipped', quantity: 0 },
        { label: '取消/退货', name: 'returned', quantity: 0 }
      ],
      activeName: 'sum',
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      searchForm: {
        orderType: 0, // 大市场订单
        warehouse: undefined,
        alOrderType: 'alOrder',
        alOrderInput: undefined,
        isWeighted: undefined,
        confirmStatus: undefined,
        pushExpense: undefined,
        paymentStatus: undefined,
        trackStatus: undefined,
        transportProduct: undefined,
        receiverType: 'consigneeCountryName',
        receiverInput: undefined,
        hasWorkOrder: undefined,
        dateRange: undefined
      },
      tableColumn: [],
      tableData: [],
      // 获取row的key值
      getRowKeys (row) {
        return row.id;
      },
      selectIds: [],
      selectRows: [],

      // 跟踪弹层
      dialogTrack: false,
      trackOrder: undefined,
      // 运费弹层
      dialogOrderExpense: false,
      orderId: undefined,

      // 分页属性
      total: 0, // 记录总条数
      pageSize: 20, // 每页显示条数
      pageIndex: 1 // 当前页
    };
  },
  watch: {
    /**
     * @date 2025/07/08
     * @author wolfMan
     * @description {tab 切换}
     */
    activeName () {
      this.search();
    }
  },
  created () {
    // 设置最近 31 天时间
    let end = `${Foundation.unixMillToDate(new Date()).split(' ')[0]} 23:59:59`;
    let start = new Date().getTime() - 3600 * 1000 * 24 * 2;
    start = `${Foundation.unixMillToDate(start).split(' ')[0]} 00:00:00`;
    this.searchForm.dateRange = [
      Foundation.unixMillToDate(start),
      Foundation.unixMillToDate(end)
    ];
  },
  mounted () {
    // 获取页面数据
    this.search();
  },
  methods: {
    /**
      * @date 2025/07/08
      * @author wolfMan
      * @description {页面查询}
    */
    search (_type) {
      let _params = this.MixinFilterParams(this.MixinClone(this.searchForm));
      if (_params.dateRange && _params.dateRange.length) {
        _params.startCreateTime = _params.dateRange[0];
        _params.endCreateTime = _params.dateRange[1];
      };
      delete _params.dateRange;
      if (!_params.alOrderInput) {
        delete _params.alOrderType;
      };
      if (!_params.receiverInput) {
        delete _params.receiverType;
      };
      _params.tabStatus = this.activeName;
      // 重置分页
      if (_type !== 'selectPage') {
        this.pageIndex = 1; // 重置翻页当前页
      };
      this.getPageData(_params);
      // 获取页面统计数据
      this.getPageTotal(_params);
    },
    /**
      * @date 2025/07/08
      * @author wolfMan
      * @description {获取页面数据}
    */
    getPageData (params) {
      let _params = {
        ...params,
        pageNum: this.pageIndex,
        pageSize: this.pageSize
      };
      API_Order.getListService(_params).then(response => {
        this.tableData = response.rows || [];
        this.total = response.total;
      });
    },
    /**
      * @date 2025/07/12
      * @author wolfMan
      * @description {获取页面统计数据}
    */
    getPageTotal (params) {
      let _params = {
        ...params,
        orderType: 0
      };
      API_Order.getOrderTotal(_params).then(response => {
        const { sum, pending_inbound, pending_outbound, shipped, returned } = response.data || {};
        this.tabList[0].quantity = sum || 0;
        this.tabList[1].quantity = pending_inbound || 0;
        this.tabList[2].quantity = pending_outbound || 0;
        this.tabList[3].quantity = shipped || 0;
        this.tabList[4].quantity = returned || 0;
      });
    },
    /**
      * @date 2025/07/10
      * @author wolfMan
      * @description {列表合计行}
    */
    getSummaries (param) {
      this.$nextTick(() => {
        this.$refs.pageTable.doLayout();
      });
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 1) {
          sums[index] = '合计';
          return;
        }
        var sumColumnArray = [
          'totalWeight',
          'totalVolume',
          'billTrafic',
          'totalExpense'
        ];
        if (sumColumnArray.indexOf(column.property) > -1) {
          const values = data.map((item) => Number(item[column.property]));
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              } else {
                return prev;
              }
            }, 0);
            sums[index] = sums[index].toFixed(2);
          }
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    /**
      * @date 2025/07/13
      * @author wolfMan
      * @description {表格行选中}
    */
    tableSelect(_row) {
      this.selectedIds = _row.map((item) => item.id);
      this.selectedRows = _row;
    },
    /**
      * @date 2025/07/11
      * @author wolfMan
      * @description {跳转订单详情}
    */
    handleDetail (_id) {
      let _route = {
        path: `/aliorder/order/detail/${_id}`
      };
      this.$router.push(_route);
    },
    /**
      * @date 2025/07/11
      * @author wolfMan
      * @description {显示跟踪弹层}
    */
    handleTrack (_row) {
      this.trackOrder = _row;
      this.dialogTrack =true;
    },
    /**
      * @date 2025/07/13
      * @author wolfMan
      * @description {显示订单运费弹层}
    */
    handleExpense (_id) {
      this.orderId = _id;
      this.dialogOrderExpense = true;
    }
  }
};
</script>